package Test.情感分析;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;

import java.util.List;
import java.util.Properties;

/**
 * @Author: kirito
 * @Date: 2025/3/23 13:13
 * @Description:
 */

public class ChineseAnalysis {
    //中文有bug
    public static void main(String[] args) {
        // 设置中文环境
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
        props.setProperty("tokenize.language", "zh");
        props.setProperty("segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz");
        props.setProperty("segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese");
        props.setProperty("segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz");
        props.setProperty("ssplit.boundaryTokenRegex", "[。？!！]");
        props.setProperty("parse.model", "edu/stanford/nlp/models/lexparser/chinesePCFG.ser.gz");

        // 构建管道
        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

        // 待分析的文本
        String text = "这家餐厅的环境很棒，服务也非常好，推荐给大家。";

        // 创建一个空的Annotation对象
        Annotation annotation = new Annotation(text);

        // 对文本进行分析
        pipeline.annotate(annotation);

        // 获取句子级别的注释
        List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);

        for (CoreMap sentence : sentences) {
            // 获取情感分析结果
            Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
            int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
            String sentimentType = sentence.get(SentimentCoreAnnotations.SentimentClass.class);

            // 输出情感分析结果
            System.out.println("句子: " + sentence);
            System.out.println("情感得分: " + sentiment);
            System.out.println("情感类型: " + sentimentType);
        }
    }
}
